package com.itheima.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.utils.R;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Description: test
 * @Create by: JJ菜菜
 * @Date: 2021/10/31 21:18
 */
// 登录验证过滤器
@WebFilter("/*")
public class FilterLogin implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String uri = request.getRequestURI();
        boolean aTrue = isTrue(uri);
        if(aTrue){
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        HttpSession session = request.getSession();
        Long id = (Long) session.getAttribute("employee");
        // 如果session中存在用户id就说名已经登录，就放行
        if(id != null){
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        String jsonString = JSON.toJSONString(R.error("NOTLOGIN"));
        servletResponse.getWriter().write(jsonString);
    }

    private boolean isTrue(String uri) {
        String[] uris = {"/backend/**", "/front/**", "/employee/login"};
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        for (String s : uris) {
            if(antPathMatcher.match(s, uri)){
                return true;
            }
        }
        return false;
    }
}
